package cn.xm.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
@Component
public class LoginFilter extends ZuulFilter {


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 获取uri
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String requestURI = request.getRequestURI();
        // 访问登录或注册页面不用校验判断
        if (requestURI.endsWith("login") || requestURI.endsWith("register")) {
            return false;
        }
        return true;

    }

    @Override
    public Object run() throws ZuulException {
        // 访问的不是登录或注册，需要判断是有token
        RequestContext currentContext = RequestContext.getCurrentContext();
        // 获取响应对象并设置字符集
        HttpServletResponse response = currentContext.getResponse();
        response.setContentType("application/json;charset=utf-8");
        // 获取请求
        HttpServletRequest request = currentContext.getRequest();
        // 获取请求头的token
        String token = request.getHeader("token");
        // 如果没有token
        if (StringUtils.isEmpty(token)) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("success",false);
            map.put("message","此用户没登录");
            map.put("resultObj","nologin");
            // 获取writer输出到响应，发送给客户端
            try {
                PrintWriter writer = response.getWriter();
                String jsonString = JSON.toJSONString(map);
                writer.write(jsonString);
                // 停止后续filter运行
                currentContext.setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }
}
